import { computed, toRef, watch } from 'vue';
import { useStore } from 'vuex';
import { goPage } from '@/utils';

export default function(orderForm: any, emits: any) {
	
	const store = useStore();
	// 地址列表
	const addressList = ref([]);
	// 选中地址
	const selectedAddress = computed(() => {
		let defaultAddress:  null = null;
		const selected = addressList.value.find((address: any) => {
			if (address.defaultFlag) {
				defaultAddress = address;
			}
			// 有选择地址返回选择地址，没有则返回默认地址
			return address.id === orderForm.memberAddressId;
		});
		return selected || defaultAddress;
	});
	// 设置选中地址
	const setAddress = (id: number): void => {
		orderForm.memberAddressId = id;
	};
	
	// 选择、添加地址
	const chooseAddress = (): void => {
		if (!addressList.value.length) {
			goPage('/pages/my/address-edit/address-edit');
		} else {
			emits('openAddress', selectedAddress.value ? selectedAddress.value.id : orderForm.memberAddressId);
		}
	};
	
	watch(
		() => selectedAddress.value,	
		(newVal) => {
			// 设置默认选中地址
			orderForm.memberAddressId = newVal ? newVal.id : 0;
		},
		{
			immediate: true,
		},
	);
	
	return {
		addressList,
		chooseAddress,
		selectedAddress,
		setAddress,
	};
}